/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ramijemli.sample.slice;

import com.ramijemli.percentagechartview.PercentageChartView;
import com.ramijemli.percentagechartview.renderer.BaseModeRenderer;
import com.ramijemli.sample.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Slider;
import ohos.agp.text.Font;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.IDialog;
import ohos.agp.window.dialog.ListDialog;
import ohos.app.Context;
import ohos.app.Environment;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.SecureRandom;

/**
 * Main ability slice
 */
public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener, Slider.ValueChangedListener {
    /**
     * The constant Fill percentage chart view
     */
    private PercentageChartView fillPercentageChartView;
    /**
     * The constant Pie percentage chart view
     */
    private PercentageChartView piePercentageChartView;
    /**
     * The constant Ring percentage chart view
     */
    private PercentageChartView ringPercentageChartView;
    /**
     * * The constant ITEMS
     */
    private static final String[] ITEMS = {"default", "interstellar.ttf", "marshmallows.ttf", "nuaz.otf", "whaleitried.ttf"};
    /**
     * The constant Select id
     */
    private int selectId = 0;
    /**
     * * The constant TEXT_STYLE_ITEMS
     */
    private static final String[] TEXT_STYLE_ITEMS = {"NORMAL", "BOLD", "ITALIC", "BOLD_ITALIC"};
    /**
     * The constant Text style select id
     */
    private int textStyleSelectId = 0;

    /**
     * On start *
     *
     * @param intent intent
     */
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        fillPercentageChartView = (PercentageChartView) findComponentById(ResourceTable.Id_fill_chart);
        piePercentageChartView = (PercentageChartView) findComponentById(ResourceTable.Id_pie_chart);
        ringPercentageChartView = (PercentageChartView) findComponentById(ResourceTable.Id_ring_chart);
        ((Slider) findComponentById(ResourceTable.Id_slider_progress)).setValueChangedListener(this);
        ((Slider) findComponentById(ResourceTable.Id_slider_startAngle)).setValueChangedListener(this);
        ((Slider) findComponentById(ResourceTable.Id_slider_bar_offset)).setValueChangedListener(this);
        findComponentById(ResourceTable.Id_btn_progress_color).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_background_color).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_gradient_colors).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_textshadow).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_textstyle).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_textfont).setClickedListener(this);
    }

    /**
     * On active
     */
    @Override
    public void onActive() {
        super.onActive();
    }

    /**
     * On foreground *
     *
     * @param intent intent
     */
    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    /**
     * On click *
     *
     * @param component component
     */
    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_btn_progress_color:
                int closeColor = Math.abs(new SecureRandom().nextInt());
                fillPercentageChartView.setProgressColor(closeColor);
                piePercentageChartView.setProgressColor(closeColor);
                ringPercentageChartView.setProgressColor(closeColor);
                break;
            case ResourceTable.Id_btn_background_color:
                int closeColor1 = Math.abs(new SecureRandom().nextInt());
                fillPercentageChartView.setBackgroundColor(closeColor1);
                piePercentageChartView.setBackgroundColor(closeColor1);
                ringPercentageChartView.setBackgroundColor(closeColor1);
                ringPercentageChartView.setBackgroundBarColor(closeColor1);
                break;
            case ResourceTable.Id_btn_gradient_colors:
                Color colors1 = new Color(Math.abs(new SecureRandom().nextInt()));
                Color colors2 = new Color(Math.abs(new SecureRandom().nextInt()));
                Color colors3 = new Color(Math.abs(new SecureRandom().nextInt()));
                Color colors4 = new Color(Math.abs(new SecureRandom().nextInt()));
                int angle = Math.abs(new SecureRandom().nextInt());
                Color[] colors = new Color[]{colors1, colors2, colors3, colors4};
                fillPercentageChartView.setGradientColors(BaseModeRenderer.GRADIENT_RADIAL, colors, new float[]{0, 0.3f, 0.7f, 1}, angle);
                piePercentageChartView.setGradientColors(BaseModeRenderer.GRADIENT_RADIAL, colors, new float[]{0, 0.3f, 0.7f, 1}, angle);
                ringPercentageChartView.setGradientColors(BaseModeRenderer.GRADIENT_RADIAL, colors, new float[]{0, 0.3f, 0.7f, 1}, angle);
                break;
            case ResourceTable.Id_btn_textshadow:
                int shadowColor = Math.abs(new SecureRandom().nextInt());
                float abs1 = Math.abs(new SecureRandom().nextFloat());
                float abs2 = Math.abs(new SecureRandom().nextFloat());
                float abs3 = Math.abs(new SecureRandom().nextFloat());
                fillPercentageChartView.setTextShadow(shadowColor, abs1, abs2, abs3);
                piePercentageChartView.setTextShadow(shadowColor, abs1, abs2, abs3);
                ringPercentageChartView.setTextShadow(shadowColor, abs1, abs2, abs3);
                break;
            case ResourceTable.Id_btn_textstyle:
                showTextStyleDialog();
                break;
            case ResourceTable.Id_btn_textfont:
                showTextFontDialog();
                break;
        }
    }

    /**
     * Show text font dialog
     */
    private void showTextFontDialog() {
        ListDialog lDialog1 = new ListDialog(getContext(), ListDialog.SINGLE);
        lDialog1.setTitleText("Select Text Font");
        lDialog1.setSingleSelectItems(ITEMS, selectId); // 0 表示默认被选中的是 index = 0 的这一项
        lDialog1.setOnSingleSelectListener((iDialog, position) -> {
            selectId = position;
            Font.Builder fontBuild1 = null;
            if (position != 0) {
                fontBuild1 = createFontBuild(getContext(), ITEMS[position]);
            }

            switch (position) {
                case 0:
                    Font.Builder fontBuild = createFontBuild(getContext(), null);
                    fillPercentageChartView.setTypeface(fontBuild);
                    piePercentageChartView.setTypeface(fontBuild);
                    ringPercentageChartView.setTypeface(fontBuild);
                    break;
                case 1:
                case 2:
                case 3:
                case 4:
                    fillPercentageChartView.setTypeface(fontBuild1);
                    piePercentageChartView.setTypeface(fontBuild1);
                    ringPercentageChartView.setTypeface(fontBuild1);
                    break;
            }
        });
        lDialog1.setButton(0, "取消", new IDialog.ClickedListener() { // 0 表示处于开始位置的按钮，1为中间，2为末尾
            @Override
            public void onClick(IDialog iDialog, int position) {
                lDialog1.destroy();
            }
        });
        lDialog1.setButton(2, "确定", new IDialog.ClickedListener() {
            @Override
            public void onClick(IDialog iDialog, int position) {
                lDialog1.destroy();
            }
        });
        lDialog1.show();
    }

    /**
     * Show text style dialog
     */
    private void showTextStyleDialog() {
        ListDialog lDialog = new ListDialog(getContext(), ListDialog.SINGLE);
        lDialog.setTitleText("Select Text Style");
        lDialog.setSingleSelectItems(TEXT_STYLE_ITEMS, textStyleSelectId); // 0 表示默认被选中的是 index = 0 的这一项
        lDialog.setOnSingleSelectListener((iDialog, position) -> {
            textStyleSelectId = position;
            switch (position) {
                case 0:
                    fillPercentageChartView.setTextStyle(BaseModeRenderer.NORMAL);
                    piePercentageChartView.setTextStyle(BaseModeRenderer.NORMAL);
                    ringPercentageChartView.setTextStyle(BaseModeRenderer.NORMAL);
                    break;
                case 1:
                    fillPercentageChartView.setTextStyle(BaseModeRenderer.BOLD);
                    piePercentageChartView.setTextStyle(BaseModeRenderer.BOLD);
                    ringPercentageChartView.setTextStyle(BaseModeRenderer.BOLD);
                    break;
                case 2:
                    fillPercentageChartView.setTextStyle(BaseModeRenderer.ITALIC);
                    piePercentageChartView.setTextStyle(BaseModeRenderer.ITALIC);
                    ringPercentageChartView.setTextStyle(BaseModeRenderer.ITALIC);
                    break;
                case 3:
                    fillPercentageChartView.setTextStyle(BaseModeRenderer.BOLD_ITALIC);
                    piePercentageChartView.setTextStyle(BaseModeRenderer.BOLD_ITALIC);
                    ringPercentageChartView.setTextStyle(BaseModeRenderer.BOLD_ITALIC);
                    break;
            }
        });
        lDialog.setButton(0, "取消", new IDialog.ClickedListener() { // 0 表示处于开始位置的按钮，1为中间，2为末尾
            @Override
            public void onClick(IDialog iDialog, int position) {
                lDialog.destroy();
            }
        });
        lDialog.setButton(2, "确定", new IDialog.ClickedListener() {
            @Override
            public void onClick(IDialog iDialog, int position) {
                lDialog.destroy();
            }
        });
        lDialog.show();
    }

    /**
     * On progress updated *
     *
     * @param slider   slider
     * @param progress progress
     * @param bool     bool
     */
    @Override
    public void onProgressUpdated(Slider slider, int progress, boolean bool) {
        switch (slider.getId()) {
            case ResourceTable.Id_slider_progress:
                fillPercentageChartView.setProgress(progress, false);
                piePercentageChartView.setProgress(progress, false);
                ringPercentageChartView.setProgress(progress, false);
                break;
            case ResourceTable.Id_slider_startAngle:
                fillPercentageChartView.setStartAngle(progress);
                piePercentageChartView.setStartAngle(progress);
                ringPercentageChartView.setStartAngle(progress);
                break;
            case ResourceTable.Id_slider_bar_offset:
                fillPercentageChartView.setBackgroundOffset(progress);
                piePercentageChartView.setBackgroundOffset(progress);
                ringPercentageChartView.setBackgroundBarThickness(progress);
                break;
        }
    }

    /**
     * On touch start *
     *
     * @param slider slider
     */
    @Override
    public void onTouchStart(Slider slider) {

    }

    /**
     * On touch end *
     *
     * @param slider slider
     */
    @Override
    public void onTouchEnd(Slider slider) {

    }

    /**
     * Create font build font . builder
     *
     * @param context context
     * @param name    name
     * @return the font . builder
     */
    Font.Builder createFontBuild(Context context, String name) {
        if (name == null) {
            return new Font.Builder("");
        }
        ResourceManager resManager = context.getResourceManager();
        RawFileEntry rawFileEntry = resManager.getRawFileEntry("resources/rawfile/" + name);
        Resource resource = null;
        try {
            resource = rawFileEntry.openRawFile();
        } catch (IOException e) {
            HiLog.error(new HiLogLabel(3, 0, "systembartint"), "%{public}s: %{public}s", BaseModeRenderer.class.getName(), e.getMessage());
        }
        StringBuffer fileName = new StringBuffer(name);
        File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName.toString());
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            int index;
            byte[] bytes = new byte[1024];
            while ((index = resource.read(bytes)) != -1) {
                outputStream.write(bytes, 0, index);
                outputStream.flush();
            }
        } catch (FileNotFoundException e) {
            HiLog.error(new HiLogLabel(3, 0, "systembartint"), "%{public}s: %{public}s", BaseModeRenderer.class.getName(), e.getMessage());
        } catch (IOException e) {
            HiLog.error(new HiLogLabel(3, 0, "systembartint"), "%{public}s: %{public}s", BaseModeRenderer.class.getName(), e.getMessage());
        } finally {
            try {
                resource.close();
                outputStream.close();
            } catch (IOException e) {
                HiLog.error(new HiLogLabel(3, 0, "systembartint"), "%{public}s: %{public}s", BaseModeRenderer.class.getName(), e.getMessage());
            }
        }
        Font.Builder builder = new Font.Builder(file);
        return builder;
    }
}
